import uniRequest from 'uni-request';

import md5 from 'js-md5';

const config = require('../config/config.js');

import {
    addMd5toHeader,
    Storage
} from '../common/utils.js';

uniRequest.defaults.baseURL = config.baseUrl;
uniRequest.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';

let noShowMsgApi=[`/api/tourist/pub/works/share`];
let showMsg=true;

function startLoading() {
    uni.showLoading({
        title: '加载中',
        mask: true
    });
}

function endLoading() {
    uni.hideLoading();
}

//声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;

function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading();
    }
    needLoadingRequestCount++;
}

function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return;
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
        endLoading();
    }
}

function showMessage(mes,showMsg) {
    if (mes && typeof mes == 'string'&&showMsg) {
        uni.showToast({
            title: mes,
            icon: 'none',
            duration: 2000
        });
    }
}

// 请求拦截
uniRequest.interceptors.request.use(request => {
        if(noShowMsgApi.includes(request.url)){
            showMsg=false
        }else{
            showFullScreenLoading();
        }
        let token = Storage.getStorage(config.tokenKey);
        if (config.isMd5 && token) {
            return addMd5toHeader(request, token);
        }
        return request;
    },
    err => {
        tryHideFullScreenLoading();
        showMessage('请求超时');
        return Promise.reject(err);
    });

// 响应拦截
uniRequest.interceptors.response.use(res => {
    tryHideFullScreenLoading();
    if (res.status === 200 && res.data) {
        if (res.data.RequestStatus === 100) {
            if (res.data.Data) {
                return res.data.Data;
            } else {
                return res.data;
            }
        }
        if (res.data.RequestStatus == 403) {
            Storage.removeStorage(config.tokenKey);
            uni.reLaunch({
                url: `/pages/tabBar/index/index`
            });
        }
        showMessage(res.data.Msg,showMsg);
        return res.data;
    } else {
        if(res.data&&res.data.Message){
            showMessage(res.data.Message,showMsg);
        }
    }
}, err => {
    tryHideFullScreenLoading();
    if (err.response.status == 504 || err.response.status == 404) {
        showMessage('服务器被吃了⊙﹏⊙∥');
    } else {
        showMessage('未知错误');
    }
    return Promise.reject(err);
});

export default uniRequest
